import router from './router/index';
import store from './store/index';
import { promiseRoutes } from './router/index';

const a = {
  path: '/',
  name: 'layout',
  component: () => import('@/views/layout'),
  redirect: 'home',
  children: []
}


router.beforeEach((to, from, next) => {
  const token = store.state.token;
  console.log(token)
  if (token) {
    if (to.path === '/login') {
      next('/home');
    } else {
      if (store.state.userInfo) {
        next();
      } else {
        store.dispatch('getUserinfo').then(res => {////getUserInfo是一个异步请求用户信息的函数
          console.log(res)
          const promiseRoutess = promiseRoutes();
          const backRouteNameList = []
          res.data.menuList.forEach(item => {
            pushName(item)
          })
          function pushName(obj) {
            if (obj.name) {
              backRouteNameList.push(obj.name)
            }
            if (obj.children && obj.children.length !== 0) {
              obj.children.forEach(item => {
                pushName(item)
              })
            }
          }
          promiseRoutess[0].children = promiseRoutess[0].children.filter(item => backRouteNameList.find(item1 => item1 === item.name))
          promiseRoutess.forEach(item => {
            router.addRoute(item)
          })
          router.replace(to.path)
        })
      }
    }
  } else {
    const needTokenList = ['/login']; //不需要token的页面
    if (needTokenList.includes(to.path)) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
    }
  }
});




